package com.mask.im.server.push;

import com.alibaba.fastjson.JSON;
import com.mask.im.server.constant.IMPushMessageConstant;
import com.mask.im.sdk.dto.IMPushMessage;
import com.mask.im.server.netty.IMChannelCtxMap;
import com.mask.im.server.netty.model.IMSendMessage;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 群组消息推送实现
 *
 * @author jian
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class IMSystemMessageProcessor extends IMAbstractPushMessage<IMPushMessage<Object>> {

    @Override
    public Boolean pushMessage(IMPushMessage<Object> receiveMessage) {
        log.info("接收到系统消息，发送者:{},接收者:{}，内容:{}", receiveMessage.getSenderId(), receiveMessage.getReceiverId(), receiveMessage.getContent());
        try {
            List<Long> receiversId = receiveMessage.getReceiversId();
            receiversId.forEach(item -> {
                Channel channel = IMChannelCtxMap.getUserIdChannel(item.toString());
                if (null != channel) {
                    IMSendMessage imSendMessage = new IMSendMessage();
                    imSendMessage.setCmd(IMPushMessageConstant.SYSTEM_MESSAGE);
                    imSendMessage.setData(receiveMessage.getContent());
                    channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(imSendMessage)));
                }
            });
            return true;
        } catch (Exception e) {
            // 消息推送失败确认
            log.error("发送异常，发送者:{},接收者:{}，内容:{}", receiveMessage.getSenderId(), receiveMessage.getReceiverId(), receiveMessage.getContent(), e);
            return false;
        }
    }
}
